Written by Dare O. on 2022-11-12
Postman Is an API platform for building, testing and also monitor APIs. Recently, a colleague was testing an API and to authorize himself had to click on the "Get New Access Token" on the parent collection before making other calls to resources available within the API collection.
So he asked if there are possibilities to automate the "Get New access tokens" when he makes HTTP calls to other resources within the API collection, and below I would like to share a method that can help achieve this.
Let's create a collection(More like a dir) to hold all the resource paths/calls for a sample API.
Postman environment variables can be treated as virtual memories to help you store values. Below is an image illustrating a quick step to create an environment variable.
Once the step above is completed, do not forget to specify the correct environment variable to be used for your collection.
Postman pre-request scripts can be used to execute JavaScript functions before a request/HTTP call is triggered to a specified resource path. Below is a short script that can help make "Get access token call", store and retrieve values from a specified environment variable.
You can add requests to the collection, and for each request, you can set its authorization/Auth type to inherit auth from parent.
RAW format for pre-request script:
var tokenCreatedAt = pm.collectionVariables.get("tokenCreatedAt");
if (!tokenCreatedAt) {
tokenCreatedAt = new Date(new Date().setDate(new Date().getDate() - 1))
}
var tokenExpiresIn = pm.collectionVariables.get("tokenExpiresIn");
if (!tokenExpiresIn) {
tokenExpiresIn = 5000;
}
var tokenCreatedTime = (new Date() - Date.parse(tokenCreatedAt))
if (tokenCreatedTime >= tokenExpiresIn) {
console.log("The token has expired. Attempting to request a new token.");
pm.sendRequest({
url: pm.variables.get("tokenURL"), // Read from enviroment variable value named tokenURL . In here you store the token endpoint.
method: 'POST',
header: {
'Accept': 'application/json',
'Content-Type': 'application/x-www-form-urlencoded'
},
body: {
mode: 'urlencoded',
urlencoded: [{
key: "username",
value: pm.environment.get("Username"), // create a new vlaue in the enviroment variable to hold API username.
},
{
key: "password",
value: pm.environment.get("Password"), // create a new vlaue in the enviroment variable to hold API password.
},
]
}
}, function(error, response) {
console.log("New access token is:"+response.json().access_token);
pm.environment.set("API_token_created_At", new Date());
pm.environment.set("API_token_jwt", response.json().access_token);
var expiresIn = response.json().expires_in;
if (expiresIn) {
tokenExpiresIn = expiresIn * 1000;
}
pm.environment.set("API_token_expires_At", tokenExpiresIn);
});
}
I hope with the short script, you can save yourself some button clicks and sometime and help in a scenario where you would like to use Postman monitors.